﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace Sundry.App_Start.WebApi
{
    /// <summary>
    ///     验证模型过滤器
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class HttpValidateModelAttribute : ActionFilterAttribute
    {
        /// <summary>
        ///  Action执行前验证
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        public override void OnActionExecuting(HttpActionContext actionContext) {
            if (actionContext.ActionArguments.Any(kv => kv.Value == null)) {
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "参数不能为空");
            }
            if (actionContext.ModelState.IsValid) return;
            else {
                //List<string> sb = new List<string>();
                StringBuilder sbBuilder = new StringBuilder();
                //获取所有错误的Key
                List<string> Keys = actionContext.ModelState.Keys.ToList();
                //获取每一个key对应的ModelStateDictionary
                foreach (var key in Keys) {
                    var errors = actionContext.ModelState[key].Errors.ToList();
                    //将错误描述添加到sb中
                    sbBuilder.Append("[");
                    foreach (var error in errors) {
                        sbBuilder.Append("{");
                        sbBuilder.Append(key).Append(":");
                        sbBuilder.Append(error.ErrorMessage);
                        sbBuilder.Append("}");
                        sbBuilder.Append(",");
                        //sb.Add(error.ErrorMessage);
                    }
                    sbBuilder.Remove(sbBuilder.Length - 1, 1);
                    sbBuilder.Append("]");
                }
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, sbBuilder.ToString());
            }
        }
    }
}